package com.wedo.mall.activity.order;

import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.e.library.activity.EActivity;
import com.e.library.http.EApi;
import com.e.library.http.EObserver;
import com.e.library.http.EResponse;
import com.e.library.utils.EGsonUtils;
import com.e.library.utils.EUtils;
import com.e.library.widget.ETitleBar;
import com.e.library.widget.decorator.EFullyLinearLayoutManager;
import com.wedo.mall.R;
import com.wedo.mall.activity.payment.PayActivity;
import com.wedo.mall.activity.user.MyAddressActivity;
import com.wedo.mall.adapter.ShoppingAdapter;
import com.wedo.mall.entity.Goods;
import com.wedo.mall.entity.MyAddress;
import com.wedo.mall.entity.Shopping;
import com.wedo.mall.util.WUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.BindString;
import butterknife.BindView;
import butterknife.OnClick;
import io.reactivex.Observable;

/**
 * @author lxy
 * @time 2017/7/28  17:50
 */
public class OrderActivity extends EActivity {

    public static final int REQ_ADDRESS = 100;
    @BindView(R.id.title_bar) ETitleBar title_bar;

    @BindView(R.id.tv_total_number) TextView tv_total_number;
    @BindView(R.id.tv_total_price1) TextView tv_total_price1;
    @BindView(R.id.tv_total_price2) TextView tv_total_price2;

    @BindView(R.id.tv_express) TextView tv_express;
    @BindView(R.id.iv_arrow) ImageView iv_arrow;
    @BindView(R.id.rl_express) RelativeLayout rl_express;
    @BindView(R.id.cb_deliver) CheckBox cb_deliver;
    @BindView(R.id.cb_take) CheckBox cb_take;

    @BindView(R.id.tv_contact) TextView tv_contact;
    @BindView(R.id.tv_phone) TextView tv_phone;
    @BindView(R.id.tv_address) TextView tv_address;
    @BindView(R.id.rl_address) RelativeLayout rl_address;
    @BindView(R.id.tv_select_address) TextView tv_select_address;

    @BindView(R.id.et_message) EditText et_message;

    @BindView(R.id.rv_shopping) RecyclerView rv_shopping;
    private ShoppingAdapter mShoppingAdapter;
    private double totalPrice;

    @BindString(R.string.order_total) String order_total;
    //@BindString(R.string.goods_price) String goods_price;
    String goods_price = "RM%.2f";
    @BindString(R.string.order_receiver) String order_receiver;
    @BindString(R.string.order_address) String order_address;

    private MyAddress mAddress;

    private String express_type = Goods.EXPRESS_0;

    @Override
    protected int layout() {
        return R.layout.activity_order;
    }

    @Override
    protected void onActivityCreated(Bundle state) {

        List<Shopping> orders = getIntent().getParcelableArrayListExtra("orders");

        rv_shopping.setHasFixedSize(true);
        rv_shopping.setLayoutManager(new EFullyLinearLayoutManager(this));
        mShoppingAdapter = new ShoppingAdapter(this,orders);
        mShoppingAdapter.checkable(false);
        mShoppingAdapter.swipe(false);
        rv_shopping.setAdapter(mShoppingAdapter);
        mShoppingAdapter.setExpress_type(express_type);
        updatePrice();

        title_bar.setOnForwardListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                defaultFinish();
            }
        });

        address();

    }

    /**根据送货方式排除商品，重新计算价格*/
    private void updatePrice(){
        int number = 0;
        totalPrice = 0.00;
        for (Shopping shopping : mShoppingAdapter.get()) {
            List<Goods> goods = shopping.goodsList;

            for (Goods g : goods) {
                if(!g.containsExpress(express_type)) {
                    continue;
                }
                number += g.goods_number;
                double price = WUtils.toDouble(g.price())*g.goods_number;
                totalPrice += price;
            }
        }

        tv_total_number.setText(String.format(order_total,number));
        String price = String.format(goods_price,totalPrice);
        tv_total_price1.setText(price);
        tv_total_price2.setText(price);
    }

    @OnClick(R.id.btn_order)
    protected void onOrderClick(){
        if (cb_deliver.isChecked() && mAddress == null){
            toast(R.string.order_address_hint);
            return;
        }

        String express_type = cb_deliver.isChecked()?Goods.EXPRESS_0:Goods.EXPRESS_1;

        List<Shopping> orders = mShoppingAdapter.get();
        int size = orders.size();
        StringBuilder ids = new StringBuilder();
        List<ParamMessage> msg = new ArrayList<>(size);
        List<ParamExpress> express = new ArrayList<>(size);

        String message = et_message.getText().toString().trim();

        boolean hasGoods = false;
        for (Shopping shopping:orders){

            List<Goods> goods = shopping.goodsList;
            if (EUtils.isEmpty(goods)){
                continue;
            }

            for (Goods g:goods){
                if(!g.containsExpress(this.express_type)) {
                    continue;
                }
                ids.append(hasGoods?",":"");
                ids.append(g.id);
                hasGoods = true;
            }

            String agent_id = goods.get(0).agent_id;

            /**留言*/
            if (!TextUtils.isEmpty(message)){
                ParamMessage pm = new ParamMessage();
                pm.agent_id = agent_id;
                pm.message = message;
                msg.add(pm);
            }


            /**送货方式*/
            ParamExpress pe = new ParamExpress();
            pe.agent_id = agent_id;
            pe.express_type = express_type;
            express.add(pe);

        }

        if(TextUtils.isEmpty(ids.toString())) {
            return;
        }

        Map<String,String> params = new HashMap<>(4);
        params.put("ids",ids.toString());
        params.put("express_content", EGsonUtils.obj2Json(express));
        if (!msg.isEmpty()){
            params.put("message",EGsonUtils.obj2Json(msg));
        }

        if (TextUtils.equals("0",express_type) && mAddress !=null){
            params.put("consignee_id",mAddress.id);
        }

        //pay_method:支付方式（0：线上，1：线下）
        params.put("pay_method","0");

        Log.i("order_params",params.toString());
        Observable<EResponse> observable = api().post(EApi.SHOPPING_COMMINT,params);
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                dismiss();

                String order = response.string("order_sn");
                Bundle bundle = new Bundle();
                bundle.putString(PayActivity.EXTRA_ORDER,order);
                bundle.putDouble(PayActivity.EXTRA_PRICE,totalPrice);
                toActivity(PayActivity.class,bundle);
                defaultFinish();

            }

            @Override
            public void failure(String msg) {
                dismiss(msg);
            }
        });
    }

    @OnClick(R.id.tv_express)
    protected void onExpressClick(){
        if (rl_express.isShown()){
            iv_arrow.setRotation(0);
            rl_express.setVisibility(View.GONE);
        }else {
            iv_arrow.setRotation(180);
            rl_express.setVisibility(View.VISIBLE);
        }
    }

    @OnClick({R.id.tv_deliver,R.id.tv_take})
    protected void onExpressCheck(TextView tv){

        switch (tv.getId()){
            case R.id.tv_deliver:
                if (mAddress !=null){
                    rl_address.setVisibility(View.VISIBLE);
                    tv_select_address.setVisibility(View.GONE);
                }else {
                    rl_address.setVisibility(View.GONE);
                    tv_select_address.setVisibility(View.VISIBLE);
                }
                iv_arrow.setRotation(0);
                tv_express.setText(tv.getText());
                rl_express.setVisibility(View.GONE);
                cb_deliver.setChecked(true);
                cb_take.setChecked(false);
                this.express_type = Goods.EXPRESS_0;
                mShoppingAdapter.setExpress_type(express_type);
                updatePrice();
                break;
            case R.id.tv_take:
                rl_address.setVisibility(View.GONE);
                tv_select_address.setVisibility(View.GONE);
                iv_arrow.setRotation(0);
                tv_express.setText(tv.getText());
                rl_express.setVisibility(View.GONE);
                cb_deliver.setChecked(false);
                cb_take.setChecked(true);
                this.express_type = Goods.EXPRESS_1;
                mShoppingAdapter.setExpress_type(express_type);
                updatePrice();
                break;
        }
    }

    @OnClick({R.id.tv_select_address,R.id.rl_address})
    protected void onSelectAddressClick(){
        toActivityForResult(MyAddressActivity.class,REQ_ADDRESS);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK && requestCode == REQ_ADDRESS){
            MyAddress address = data.getParcelableExtra(MyAddressActivity.EXTRA_ADDRESS);
            onSelectedAddress(address);
        }
    }

    private void onSelectedAddress(MyAddress address){
        this.mAddress = address;
        tv_phone.setText(address.telephone);
        tv_contact.setText(String.format(order_receiver,address.consignee));
        tv_address.setText(String.format(order_address,address.address));
        rl_address.setVisibility(View.VISIBLE);
        tv_select_address.setVisibility(View.GONE);
    }

    private class ParamMessage{
        public String agent_id;
        public String message;
    }

    private class ParamExpress{
        public String agent_id;
        public String express_type;
    }

    private void address(){
        Observable<EResponse> observable = api().post(EApi.USER_AllCONSIGNEE,new HashMap<String, String>(1));
        observer(observable, new EObserver() {
            @Override
            public void successful(EResponse response) {
                List<MyAddress> addresses = response.list(MyAddress.class);
                if (EUtils.isEmpty(addresses)){
                    return;
                }
                for (MyAddress address:addresses){
                    if (address.isDefault()){
                        onSelectedAddress(address);
                        break;
                    }
                }
            }

            @Override
            public void failure(String msg) {

            }
        });
    }

}
